/*
 * @Author: 黄威
 * @Date: 2022-09-15 16:59:46
 * @LastEditors: 黄威
 * @LastEditTime: 2023-02-24 10:53:16
 * @Description: react相关的工具方法
 */
import React from 'react';
import { render as reactRender, unmount as reactUnmount } from 'rc-util/lib/React/render';

/**
 * 动态渲染模态框的一个方法
 * @param ModalType 模态框组件
 * @param props 属性
 */
export function renderModal(ModalType: any, config: any = {}, customContainer?: Element) {
  const container = customContainer ?? document.createDocumentFragment();
  let currentConfig = { ...config, onCancel: close, open: true } as any;

  function render(props) {
    const modal = React.createElement(ModalType, { ...props, ...config });
    return reactRender(modal, container);
  }
  function destroy() {
    reactUnmount(container);
  }
  function close() {
    currentConfig = {
      ...currentConfig,
      open: false,
      afterClose: () => {
        if (typeof config.afterClose === 'function') {
          config.afterClose();
        }

        destroy();
      },
    };
    render(currentConfig);
  }

  render(currentConfig);

  return { close };
}
